package com.action.ui.activity;

import android.support.constraint.ConstraintLayout;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.action.childbase.ChildBaseActivity;
import com.action.entity.Redpacket;
import com.action.service.pressenter.RedpakcetPressenter;
import com.action.ui.fragment.RedMapFrament;
import com.action.ui.view.PasswordView;
import com.action.utils.Rotate3dAnimation;
import com.action.utils.SingleClick;
import com.action.utils.SoftKeyBoardListener;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.base.app_core.base.ActionPacketView;
import com.base.app_core.service.user.model.User;
import com.base.app_core.util.AppConstants;
import com.base.app_core.util.XYBAUtils;
import com.base.app_core.util.MD5Util;
import com.blankj.utilcode.util.StringUtils;
import com.daimajia.androidanimations.library.Techniques;
import com.daimajia.androidanimations.library.YoYo;
import com.xinglai.yun.R;
import com.nineoldandroids.animation.ObjectAnimator;
import com.tencent.map.lib.util.StringUtil;

import javax.inject.Inject;

import butterknife.BindView;
import butterknife.OnClick;


@Route(path = AppConstants.ROUTEURI.OPEN_PACKET)
public class OpenPacketActivity extends ChildBaseActivity<RedpakcetPressenter> implements
        ActionPacketView.RedPacketView, SoftKeyBoardListener.OnSoftKeyBoardChangeListener, ActionPacketView.PacketTimeAction, PasswordView.PasswordListener {

    public static final int COUNT_TIME = 0X255;
    public static final int PARSE_EEROR = 0X355;
    public static final int COUNT_AD_TIME = 0x888;
    public static final int INVALID_CORRENT = 0x666;
    public static final int VIEW_OPEN_STATE = 0x999;

    @BindView(R.id.container)
    ConstraintLayout container;

    @BindView(R.id.logo)
    ImageView mlogo;

    @BindView(R.id.name)
    TextView mname;

    @BindView(R.id.pswView)
    PasswordView mpswView;

    @BindView(R.id.open)
    ImageView open;

    @BindView(R.id.pwd_time)
    TextView pwdTime;

    @BindView(R.id.pwd_hint)
    TextView pwdHint;

    @Inject
    User user;

    @BindView(R.id.note)
    TextView note;

    private SoftKeyBoardListener softKeyBoardListener;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_open_packet;
    }

    @Override
    protected void setupComponent() {
        super.setupComponent();
        getChildViewComponent().inject(this);
    }

    Redpacket redpacket = null;

    @Override
    protected void initView() {
        super.initView();
//        这个会导致向上偏移
        getWindow().setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
        ViewGroup.LayoutParams layoutParams = container.getLayoutParams();
        layoutParams.width = (int) (XYBAUtils.getScreenWidth() * 0.9);
        container.setLayoutParams(layoutParams);
        mpswView.setPasswordListener(this);
        softKeyBoardListener = new SoftKeyBoardListener(this);
        softKeyBoardListener.setListener(this, this);
    }
    @Override
    protected void initData() {
        super.initData();
        redpacket = getIntent().getParcelableExtra(RedMapFrament.OPEN_PACKAGE);
        if (null == redpacket) {
            finish();
            return;
        }
        String wxIcon = redpacket.getWxIcon();
        if (StringUtil.isEmpty(wxIcon)) {
            mlogo.setImageResource(R.mipmap.ic_xyb_logo_round);
        } else {
            XYBAUtils.displayCircleImage(this, wxIcon, mlogo);
        }
        String wxNickname = redpacket.getWxNickname();
        if (StringUtils.isEmpty(wxNickname)) {
            mname.setText("系统红包");
        } else {
            mname.setText(wxNickname);
        }

        if (redpacket.getType() != null) {
            int type = redpacket.getType().intValue();
            initViewByType(type);
        }else initViewByType(1);
    }

    private void initViewByType(int type) {
        switch (type) {
            case 0:
                note.setText("给你发了一个红包");
                open.setVisibility(View.VISIBLE);
                mpswView.setVisibility(View.INVISIBLE);
                pwdTime.setVisibility(View.INVISIBLE);
                pwdHint.setVisibility(View.INVISIBLE);
                container.setBackground(getResources().getDrawable(R.drawable.shape_red_round_rec_8));
                break;
            case 1:
                note.setText("给你发了一个红包");
                open.setVisibility(View.INVISIBLE);
                mpswView.setVisibility(View.VISIBLE);
                pwdTime.setVisibility(View.VISIBLE);
                pwdHint.setVisibility(View.INVISIBLE);
                container.setBackground(getResources().getDrawable(R.mipmap.hongbaobeijing));
                mPresenter.getTimeCount(redpacket.getCreatedAt());
                break;
            case 2:
                note.setText("给你发了一个红包");
                open.setVisibility(View.VISIBLE);
                mpswView.setVisibility(View.INVISIBLE);
                pwdTime.setVisibility(View.INVISIBLE);
                pwdHint.setVisibility(View.INVISIBLE);
                container.setBackground(getResources().getDrawable(R.mipmap.hongbaobeijing));
                break;
        }
    }

    @OnClick(R.id.open)
    public void openNewRedPacket() {
        if (SingleClick.isSingle()) {
            setOpenView();
            showProgress();
            if (null != mPresenter) {
                mPresenter.openRedPacket(redpacket.getSn(), null, redpacket.getType());
            }
        } else {
            showToast("不要重复查看同一个红包");
        }
    }

    @OnClick(R.id.close)
    public void close() {
        finish();
    }

    private void setOpenView() {
        if (open.getVisibility() == View.VISIBLE) {
//            RotateAnimation rotate  = new RotateAnimation(0f, 360f, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
//            LinearInterpolator lin = new LinearInterpolator();
//            rotate.setInterpolator(lin);
//            rotate.setDuration(2000);//设置动画持续周期
//            rotate.setRepeatCount(-1);//设置重复次数
//            rotate.setFillAfter(true);//动画执行完后是否停留在执行完的状态
//            rotate.setStartOffset(10);//执行前的等待时间

//            open.setAnimation(rotate);
//            rotateOnYCoordinate();
        }
    }


    // 以X轴为轴心旋转
    private void rotateOnYCoordinate() {
        float centerX = open.getWidth() / 2.0f;
        float centerY = open.getHeight() / 2.0f;
        float centerZ = 0f;
        Rotate3dAnimation rotate3dAnimationX = new Rotate3dAnimation(0, 180, centerX, centerY, centerZ, Rotate3dAnimation.ROTATE_Y_AXIS, true);
        rotate3dAnimationX.setDuration(1000);
        open.startAnimation(rotate3dAnimationX);
    }

    @Override
    public void notifyError(String errorCode, String content) {
        if ("1009".equals(errorCode)) {
            pwdHint.setText(content);
            pwdHint.setVisibility(View.VISIBLE);
            YoYo.with(Techniques.Flash).repeat(1).playOn(pwdHint);
        } else {
            super.notifyError(errorCode, content);
        }
    }

    @Override
    public void doingOpen() {
        showToast("正在打开");
        mlogo.postDelayed(new Runnable() {
            @Override
            public void run() {
                showProgress();
            }
        }, 500);
    }

    @Override
    public void doOpenSuccess() {
        showToast("打开成功");
        open.clearAnimation();
        this.getRootView(this).postDelayed(new Runnable() {
            @Override
            public void run() {
                Integer type = redpacket.getType();
//                if (type == 2) {
                    ARouter.getInstance().build(AppConstants.ROUTEURI.BASE_AD_VIEW).withString("sn", redpacket.getSn())
                            .withBoolean("fromOpen", true).navigation();
                    OpenPacketActivity.this.finish();
//                } else {
//                    ARouter.getInstance().build("/redpacket/detail").withString("sn", redpacket.getSn())
//                            .withInt("type", type).withBoolean("fromOpen", true).navigation();
//                    OpenPacketActivity.this.finish();
//                }
            }
        }, 100);
    }

    @Override
    public void keyBoardShow(int height) {
        ObjectAnimator translationY = ObjectAnimator.ofFloat(findViewById(android.R.id.content), "translationY",
                0, shouTranY(height));
        translationY.setDuration(AppConstants.ANI_DIALOG_FLOATING_TOP);
        translationY.start();
    }

    @Override
    public void keyBoardHide(int height) {
        ObjectAnimator translationY = ObjectAnimator.ofFloat(findViewById(android.R.id.content), "translationY",
                shouTranY(height), 0);
        translationY.setDuration(AppConstants.ANI_DIALOG_FLOATING_TOP);
        translationY.start();
    }


    private int shouTranY(int height) {
        return -height + (XYBAUtils.getWindowHeight() - container.getHeight()) / 3;
    }

    /**
     * count 位0 的时候超时变成普通红包
     *
     * @param count
     */
    @Override
    public void onTimeCount(long count) {
        if (count < 0) {
            initViewByType(0);
            mPresenter.stopHandleMessage();
        } else {
            long m = count / 1000;
            StringBuffer buffer = new StringBuffer();
            long fen = m / 60;
            long miao = m % 60;
            buffer.append("密码限时:");
            if (fen < 10) {
                buffer.append("0").append(fen);
            } else {
                buffer.append(fen);
            }
            buffer.append(":");
            if (miao < 10) {
                buffer.append("0").append(miao);
            } else {
                buffer.append(miao);
            }

            pwdTime.setText(buffer.toString());
        }
    }

    @Override
    public void onParseError() {
        pwdTime.setVisibility(View.GONE);
    }

    @Override
    public void passwordChange(String changeText) {
    }

    @Override
    public void passwordComplete() {
        setOpenView();
        if (null != mPresenter) {
            mPresenter.openRedPacket(redpacket.getSn(), MD5Util.encrypt(mpswView.getPassword()), redpacket.getType());
        }
    }

    @Override
    public void keyEnterPress(String password, boolean isComplete) {

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }
}
